import React, { Component } from 'react';
import { observer } from 'mobx-react';
import { Input as AntInput, Tooltip } from 'antd';
import '../base.css';

@observer
class InputFormat extends Component {
  constructor() {
    super();
    this.handleBlur = this.handleBlur.bind(this);
    this.handleFocus = this.handleFocus.bind(this);
  }
  handleBlur() {
    const { validator, value, onBlur, formatter } = this.props;
    if (validator) validator.touched = true;
    if(onBlur) onBlur();
    this.view.refs.input.value = formatter(value);
  }
  handleFocus() {
    const { value, onFocus } = this.props;
    if(onFocus) onFocus();
    this.view.refs.input.value = value
  }
  render() {
    const { validator, value, onBlur, onFocus, formatter, ...rest, } = this.props;
    let hasError = false;
    if (validator) {
      if (validator.touched && validator.error) {
        hasError = true;
      }
    }
    return (
      <Tooltip placement="topLeft" title={hasError ? validator.error : ''}>
        <div className={hasError ? 'has-error' : ''}>
          <AntInput
            {...rest}
            value={value}
            onBlur={this.handleBlur}
            ref={view => this.view = view}
            onFocus={this.handleFocus}
          />
        </div>
      </Tooltip>
    );
  }
}

export default InputFormat;
